package com.itheima.Demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class Demo异步非阻塞读取 {//异步非阻塞read()
    public static void main(String[] args) throws IOException {
        //创建对象
        AsynchronousServerSocketChannel assc  = AsynchronousServerSocketChannel.open();
        //绑定端口
        assc.bind(new InetSocketAddress(1456));
        //连接客户端
        assc.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel sc, Object o) {
                //创建数组
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                //读取数据
                //异步非阻塞读取
                sc.read(buffer, null, new CompletionHandler<Integer, Object>() {
                    @Override
                    public void completed(Integer len, Object o) {
                        System.out.println(new String(buffer.array(),0,len));

                    }

                    @Override
                    public void failed(Throwable throwable, Object o) {

                    }
                });

            }

            @Override
            public void failed(Throwable throwable, Object o) {

            }
        });

    }
}
